from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QMessageBox
import time, serial
import serial.tools.list_ports
from serial.tools.list_ports import comports

ser = 0


class SerialThread(QThread):
    Serialdata = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.last_data = None
        self.running = True  # 添加一个运行标志

    def run(self):
        while self.running:  # 检查运行标志
            if ser and ser.is_open:
                try:
                    data = ser.readline().decode('utf-8', errors='ignore').strip()
                except Exception as e:
                    continue
                if data and data != self.last_data:
                    self.Serialdata.emit(data)
                    self.last_data = data
            time.sleep(0.01)

    def stop(self):  # 添加停止方法
        self.running = False  # 设置运行标志为 False

    def open_serial(self, port, baudrate):
        if port == '':
            QMessageBox.critical(self, '串口异常', '       打开串口失败！！！\n请选择正确的串口或该串口被占用')
        else:
            try:
                global ser
                ser = serial.Serial(port, baudrate)
                self.pushButton_4.setText("关闭串口")
                self.jyuiInit()
                if self.uart_thread is None or not self.uart_thread.isRunning():
                    self.uart_thread = SerialThread()
                    self.uart_thread.start()
                    ser.rts = False
                    ser.dtr = False
                else:
                    pass
            except Exception:
                QMessageBox.critical(self, '串口异常', '       打开串口失败！！！\n请选择正确的串口或该串口被占用')

    def close_serial(self):
        global ser
        if ser:
            ser.close()
            ser = None  # 将 ser 设置为 None
            if self.uart_thread is not None:
                self.uart_thread.stop()  # 停止线程
                self.uart_thread.quit()  # 退出线程
                self.uart_thread.wait()  # 等待线程结束
                self.uart_thread = None  # 清理线程
        else:
            pass

    def update_port_list(ui):
        ports = [port.device for port in comports()]
        ui.comboBox_3.clear()
        ui.comboBox_3.addItems(ports)

    def send_mkfsdata(self):
        if ser:
            if ser.is_open:
                try:
                    ser.write("mkfsTest".encode('gbk'))
                except Exception:
                    print("uart write error!!!")
                    pass
        else:
            QMessageBox.warning(self, "警告", "请打开串口!", QMessageBox.Ok)

    def send_startdata(self):
        if ser:
            if ser.is_open:
                try:
                    ser.write("startTest".encode('gbk'))
                except Exception:
                    print("uart write error!!!")
                    pass
        else:
            QMessageBox.warning(self, "警告", "请打开串口!", QMessageBox.Ok)

    def send_stopdata(self):
        if ser:
            if ser.is_open:
                try:
                    ser.write("stopTest".encode('gbk'))
                except Exception:
                    print("uart write error!!!")
                    pass
        else:
            QMessageBox.warning(self, "警告", "请打开串口!", QMessageBox.Ok)

    def send_uartFundata(self, data):
        if ser:
            if ser.is_open:
                try:
                    ser.write(data.encode('gbk'))
                except Exception:
                    print("uart write error!!!")
                    pass
        else:
            QMessageBox.warning(self, "警告", "请打开串口!", QMessageBox.Ok)

    def send_bluedata(self):
        if ser:
            if ser.is_open:
                try:
                    ser.write("blueTest".encode('gbk'))
                except Exception:
                    print("uart write error!!!")
                    pass
        else:
            pass

    def send_beepdata(self):
        if ser:
            if ser.is_open:
                try:
                    ser.write("beepTest".encode('gbk'))
                except Exception:
                    print("uart write error!!!")
                    pass
        else:
            pass


# 实时检测可用串口
class SerialPortMonitorThread(QThread):
    SerialPort = pyqtSignal(list)

    def __init__(self):
        super().__init__()

    def run(self):
        while True:
            ports = [port.device for port in comports()]
            self.SerialPort.emit(ports)
            time.sleep(1)  # 每1秒更新一次可用串口列表
